package com.example.demo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * @author calwen
 * @since 2023/9/19
 */
@Component
@Service
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

    private static final Map<String, Session> sessionPool = new HashMap<>();

    /**
     * 接收创建会话请求
     *
     * @param userId key
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        //存入会话
        sessionPool.put(userId, session);
        log.info("websocket消息: 有新的连接 userId={} ，总数为= {}", userId, sessionPool.size());
    }

    /**
     * 监听收到消息
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("websocket消息: 收到 message={}", message);
    }

    /**
     * 推送消息给客户端
     *
     * @param userId  会话 key
     * @param message 消息
     */
    public void pullClient(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session == null || !session.isOpen()) {
            log.info("websocket消息: 未开启会话");
            return;
        }
        log.info("websocket消息: 推送消息 message = {} ", message);
        session.getAsyncRemote().sendText(message);
    }

}
